import * as Icons from '@ant-design/icons';
import { dropByCacheKey, history, useLocation } from '@umijs/max';
import { Tabs, TabsProps, message } from 'antd';
import classNames from 'classnames';
import { useCallback, useEffect, useState, type FC } from 'react';
import routes from '../../../config/routes';
import EllipsisTooltip from '../EllipsisTooltip';
import styles from './index.less';
import TabCloseIcon from './TabCloseSvg';
import TabIcon from './TabIconSvg';

interface PubTabsProps {
  children?: React.ReactNode;
}

// tab项类型
interface TabItemProps {
  label: React.ReactNode | string;
  key: string;
  icon?: string | React.ReactNode;
  inCache?: boolean; // 是否需要缓存
}

const DynamicComponent = ({ componentName }: { componentName: string }) => {
  const IconComponent = Icons[componentName];
  return IconComponent ? <IconComponent /> : null;
};

const PubTabs: FC<PubTabsProps> = (props) => {
  // 从路由表中筛选出所有需要显示在tab上的路由
  const tabs = routes
    ?.filter((i) => !i?.hideInTab)
    .map((j) => ({ label: j.name, key: j.path, icon: j.icon || '', ...j }));
  const location = useLocation();
  const [activeTab, setActiveTab] = useState<TabItemProps>();
  const [tabItems, setTabItems] = useState<TabItemProps[]>([]);

  // 添加tabItems
  const handleAddItems = (val: any) => {
    const isExist = tabItems.some((i) => i.key === val.path);
    if (!isExist) {
      setTabItems((preState) => [...preState, val]);
    }
  };

  // 删除tab
  const handleCloseTab = (key: string) => {
    // 至少保留一个tab
    if (tabItems.length < 2) {
      message.error('至少保留一个tab！');
      return;
    }
    if (key === activeTab?.key) {
      // 清空当前页的缓存状态
      if (activeTab?.inCache) {
        dropByCacheKey(key);
      }
      /*
       * 删除当前选中的tab时：
       * 1. 如果当前tab是第一个自动，自动选中后一个
       * 2. 不是第一个自定选中前一个
       */
      const i = tabItems.findIndex((j) => j.key === key);
      const nextTab = tabItems[i === 0 ? i + 1 : i - 1];
      history.push(nextTab.key);
    }
    setTabItems((preState) => {
      return preState.filter((m) => m.key !== key);
    });
  };
  const renderTabBar: TabsProps['renderTabBar'] = useCallback(
    (props: any, DefaultTabBar: any) => {
      const { activeKey } = props;
      return (
        <DefaultTabBar {...props}>
          {(node: any) => {
            const tabItem = tabItems.find((i) => i.key === node.key) as any;
            return (
              <div
                {...node.props}
                className={classNames([
                  styles.tabs_item,
                  {
                    [styles.tabs_item_checked]: activeKey === tabItem?.key,
                  },
                ])}
              >
                <div className={classNames([styles.svg_wrap])}>
                  <TabIcon className={styles.svg_icon} />
                </div>
                <div className={styles.panel_wrap}>
                  <div className={styles.tab_icon}>
                    {tabItem?.icon && (
                      <DynamicComponent componentName={tabItem?.icon} />
                    )}
                  </div>
                  <div className={styles.tab_text}>
                    <EllipsisTooltip text={tabItem?.label} />
                  </div>
                  <div
                    className={styles.tab_close}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleCloseTab(tabItem?.key);
                    }}
                  >
                    <TabCloseIcon />
                    {/* <Icons.CloseOutlined /> */}
                  </div>
                </div>
                <div className={styles.divider}></div>
              </div>
            );
          }}
        </DefaultTabBar>
      );
    },
    [tabItems, activeTab],
  );

  useEffect(() => {
    if (location.pathname !== activeTab?.key) {
      // 结合路由筛选出当前选中的tab
      const activeTabItem = tabs.find((i) => i.path === location.pathname);
      if (activeTabItem) {
        setActiveTab(activeTabItem);
        // 新增tabs
        handleAddItems(activeTabItem);
      }
    }
  }, [tabs, location]);

  return (
    <div className={styles.pubTabs_wrap}>
      {/* <Button
        type="primary"
        onClick={() => {
          const nextActiveTab = {
            label: `table - ${Math.random()}`,
            key: Math.random().toString(),
          };
          setTabItems((preState) => [...preState, nextActiveTab]);
          setActiveTab(nextActiveTab);
        }}
      >
        增加标签
      </Button> */}
      <Tabs
        hideAdd
        onChange={(key: string) => {
          history.push(key);
        }}
        activeKey={activeTab?.key}
        type="editable-card"
        items={tabItems}
        renderTabBar={renderTabBar}
      />
    </div>
  );
};

export default PubTabs;
